<?php

namespace app\admin\controller\applyform;

use app\common\controller\Backend;
use fast\Tree;
use think\Db;

/**
 * 
 *
 * @icon fa fa-file
 */
class Apply extends Backend
{
    
    /**
     * Apply模型对象
     */
    protected $model = null;
    protected $noNeedRight=["lists","status","getSubjectNames","studentList"];
    protected $noNeedLogin=["lists","status","getSubjectNames","studentList"];


    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Apply');
        $this->modelValidate = true;
    }
    
    /**
     * 获取报名学员列表
     * @return \think\response\Json
     */
    public function studentList()
    {
        try {
            $applyId = $this->request->get('apply_id/d', 0);
            if (!$applyId) {
                return json(['code' => 0, 'msg' => '缺少报名ID']);
            }
            
            // 查询报名信息
            $apply = $this->model->where('id', $applyId)->find();
            if (!$apply) {
                return json(['code' => 0, 'msg' => '报名信息不存在']);
            }

            // 查询报名学员数据
            $applyFormItemModel = new \app\admin\model\ApplyFormItem();
            $applyFormItems = $applyFormItemModel
                ->alias('a')
                ->join('fa_order o', 'a.order_id = o.id', 'LEFT')
                ->join('fa_user u', 'a.user_id = u.id', 'LEFT')
                ->field('a.id,a.intro as course_name,a.create_time,o.amount,o.payment_status,o.pay_time,o.order_sn,u.username,u.mobile,u.gender,u.avatar')
                ->select();

            // 检查查询结果
            if (empty($applyFormItems)) {
                return json(['code' => 0, 'msg' => '暂无报名学员数据']);
            }

            // 处理结果
            $result = [];
            foreach ($applyFormItems as $item) {
                $result[] = [
                    'id' => $item['id'],
                    'username' => $item['username'] ?? '', // 用户名
                    'mobile' => $item['mobile'] ?? '', // 手机号
                    'gender' => $item['gender'] ?? '-', // 性别
                    'avatar' => $item['avatar'] ?? '', // 头像
                    'create_time' => $item['create_time'] ? $item['create_time'] : '', // 创建时间
                    'amount' => $item['amount'] ?? '0.00', // 金额
                    'payment_status' => $item['payment_status'] ?? 0, // 支付状态
                    'pay_time' => $item['pay_time'] ? date('Y-m-d H:i:s', $item['pay_time']) : '', // 支付时间
                    'order_sn' => $item['order_sn'] ?? '', // 订单号
                    'course_name' => $item['course_name'] ?? '' // 课程名称
                ];
            }
    
            // 使用FastAdmin的标准返回格式
            return json([
                'code' => 1,
                'msg' => '获取成功',
                'data' => [
                    'list' => $result,
                    'total' => count($result)
                ]
            ]);
        } catch (\Exception $e) {
            trace("查询学员列表错误: " . $e->getMessage(), 'error');
            return json(['code' => 0, 'msg' => '查询学员列表失败']);
        }
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            
            // 获取城市和学校筛选参数
            $city_id = $this->request->get('city_id', 0);
            $school_id = $this->request->get('school_id', 0);
            
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                ->where($where);

            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $total = $total->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            
            // 添加城市和学校筛选条件
            if ($city_id > 0) {
                $total = $total->where('city_id', $city_id);
            }
            if ($school_id > 0) {
                $total = $total->where('school_id', $school_id);
            }
            
            $total = $total
                ->count();

            $list = $this->model
                ->where($where);
            //if ($_SESSION['think']['admin']['group_id'] == 2) {
            //    $list = $list->where("city_id", "=", $_SESSION['think']['admin']['city_id']);
            //}
            
            // 添加城市和学校筛选条件
            if ($city_id > 0) {
                $list = $list->where('city_id', $city_id);
            }
            if ($school_id > 0) {
                $list = $list->where('school_id', $school_id);
            }
            
            $list = $list->where("status", "<>", -1)
                ->order('weigh desc,id desc')
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            //$this->model->getLastSql();
            $list = collection($list)->toArray();

//            $tree = Tree::instance();
//            $tree->init($list, 'pid');
//            $list = $tree->getTreeList($tree->getTreeArray(0), 'name');
//            $data = array();
//            for ($i = 0; $i < count($list); $i++) {
//                $v = $list[$i];
//                $data[] = [
//                    'id' => $v['id'],
//                    'parent' => $v['pid'] ? $v['pid'] : '#',
//                    'name' => $v['name'],
//                    'type' => $v['type'],
//                    'status' => $v['status'],
//                    'school_id' => model("School")->getSchool_idTextAttr($v['school_id'])
//                ];
//            }


            for($i=0;$i<count($list);$i++){
//                $list[$i]['province_id']=model('Cityarea')->getProvince_idTextAttr($list[$i]['province_id']);
                $list[$i]['city_id']=model('Cityarea')->getCity_idTextAttr($list[$i]['city_id']);
                $list[$i]['school_id']=model('School')->getSchool_idTextAttr($list[$i]['school_id'],$list[$i]);
                //$v['table_id']=$this->model->getTable_idTextAttr($v['table_id'],$v);
                $list[$i]['table_id']=$this->model->getTable_idTextAttr($list[$i]['table_id'],$list[$i]);
                //$v['is_real']=$this->model->getIs_realTextAttr($v['is_real'],$v);
                $list[$i]['is_real']=$this->model->getIs_realTextAttr($list[$i]['is_real'],$list[$i]);
                //$v['is_close']=$this->model->getIs_closeTextAttr($v['is_close'],$v);
                $list[$i]['is_close']=$this->model->getIs_closeTextAttr($list[$i]['is_close'],$list[$i]);
                //$v['is_opened']=$this->model->getIs_openedTextAttr($v['is_opened'],$v);
                $list[$i]['is_opened']=$this->model->getIs_openedTextAttr($list[$i]['is_opened'],$list[$i]);
                //$v['is_finished']=$this->model->getIs_finishedTextAttr($v['is_finished'],$v);
                $list[$i]['is_finished']=$this->model->getIs_finishedTextAttr($list[$i]['is_finished'],$list[$i]);
                //$v['is_user_end']=$this->model->getIs_user_endTextAttr($v['is_user_end'],$v);
                $list[$i]['is_user_end']=$this->model->getIs_user_endTextAttr($list[$i]['is_user_end'],$list[$i]);
                //$v['is_end']=$this->model->getIs_endTextAttr($v['is_end'],$v);
                $list[$i]['is_end']=$this->model->getIs_endTextAttr($list[$i]['is_end'],$list[$i]);
                $list[$i]['apply_type']=$this->model->getApply_typeTextAttr($list[$i]['apply_type'],$list[$i]);
            }
            
            
            $result = array("total" => $total, "rows" => $list);
            return json($result);
        }

        Db::execute("UPDATE eb_apply_form_item AS a
INNER JOIN fa_order AS o ON a.user_id = o.user_id AND a.classes_id = o.classes_id
SET a.order_id = o.id WHERE a.order_id IS NULL");
        
//        $this->assignconfig("relType",$_REQUEST['relType']);
//        $this->assignconfig("relId",$_REQUEST['relId']);
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        return $this->view->fetch();
    }
    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $user=$this->auth->getUserInfo();
            $params = $this->request->post("row/a");

            if ($params) {
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        //$this->model->validate($validate);
                    }
                    
                    // 处理分阶段报名字段
                    $this->processStagedFields($params);
                    
                    // 处理主要的时间字段
                    $this->processTimeFields($params);
                    if (isset($params['class_items']) && is_array($params['class_items'])) {
                        $params['class_items'] = json_encode($params['class_items']);
                    }
                    $datatime=date("Y-m-d H:i:s");
                    $params['create_time']=$datatime;
                    $params['status']=1;
                    $params['city_id']= $user['city_id'];
                    $params['school_id']= $user['school_id'];
                    unset($params['delete_time']);
                    unset($params['update_time']);
                    $result = $this->model->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($this->model->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        $start_time=date('Y-m-d H:i:s');
        $this->view->assign("start_time", $start_time);
        $end_time=date('Y-m-d H:i:s', strtotime("+2 month"));
        $this->view->assign("end_time", $end_time);
        $add_time=time();
        $this->view->assign("add_time", $add_time);
        $dead_time=date('Y-m-d H:i:s', strtotime("+1 year"));
        $this->view->assign("dead_time", $dead_time);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = NULL)
    {
        $row = $this->model->get($ids);
        $user=$this->auth->getUserInfo();
        if (!$row)
        $this->error(__('No Results were found'));
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        //$row->validate($validate);
                    }
                    
                    // 处理分阶段报名字段
                    $this->processStagedFields($params);
                    
                    // 处理主要的时间字段
                    $this->processTimeFields($params);
                    
                    $datatime=date("Y-m-d H:i:s");
                    $params['update_time']=$datatime;
                    $params['city_id']= $user['city_id'];
                    $params['school_id']= $user['school_id'];
                    $params['special_channel_classes']= join(",",$params['special_channel_classes']);
                    unset($params['delete_time']);
                    unset($params['create_time']);
//                    if($_SESSION['think']['admin']['group_id']==2){
//                        $params['city_id']=$_SESSION['think']['admin']['city_id'];
//                    }
                    if (isset($params['class_items']) && is_array($params['class_items'])) {
                        $params['class_items'] = json_encode($params['class_items']);
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success("保存成功",null,['refash' => true]);
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->assignconfig("admin",$_SESSION['think']['admin']);
        //print_r($_SESSION['think']['admin']);exit;
        $classList=json_decode($row['class_items'], true);
        if (is_array($classList)) {
            $this->view->assign($classList);
        }
        $this->view->assign("row", $row);
        $this->view->assign("apply_id", $ids);
        return $this->view->fetch();

    }

    /**
     * 添加
     */
    public function view($ids = NULL)
    {
        $row=$this->model->getRow($ids);
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    public function lists($ids = NULL){
        $where="where 1=1";
        if($_SESSION['think']['admin']['group_id']!=1){
            $where.=" and city_id='{$_SESSION['think']['admin']['city_id']}'";
        }
        $page=1;
        $pagesize=50;
        if ($this->request->isAjax()) {
            if ($this->request->request('keyField')) {
                $keyField = $this->request->request("keyField");
                $keyValue = $this->request->request("keyValue");
                $page = $this->request->request("pageNumber");
                $page = ($page == null) ? 1 : $page;
                $pagesize = $this->request->request("pageSize");
                $pagesize = ($pagesize == null) ? 10 : $pagesize;
                if ($keyValue != "") {
                    $nn=preg_split("/\,/",$keyValue);
                    for($i=0;$i<count($nn);$i++) {
                        $where.= " and $keyField='{$nn[$i]}'";
                    }
                }
            }else{
                $where="where 1=1";
                if(isset($_REQUEST['city_id'])&&$_REQUEST['city_id']>0){
                    //$where.=" and city_id=".$_REQUEST['city_id'];
                }
            }
        }
        $sql="select id,title name from dev002_gxyusheng.apply_form $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
        $list = db()->query($sql);

//        $r_name = model("School")->field("id,name")->where("id", "=", $_REQUEST['school_id'])->select();
//        if (empty($list)&&!empty($r_name)) {
//            $data = array(
//                "type" => "file",
//                "pid" => 0,
//                "name" => $r_name[0]['name']."学科",
//                "title" => $r_name[0]['name'],
//                "ismenu" => 0,
//                "createtime" => time(),
//                "updatetime" => time(),
//                "status" => 1,
//                "school_id" => $_REQUEST['school_id'],
//            );
//            $this->model->create($data);
//        }
//        $sql="select id,pid,name,title,status from dev002_gxyusheng.apply_form $where limit " . (($page - 1) * $pagesize) . ",$pagesize";
//        $list = db()->query($sql);
//        $tree = Tree::instance();
//        $tree->init($list, 'pid');
//        $list = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $total = db()->query("select count(1) as c from  dev002_gxyusheng.apply_form $where")[0];
        echo json_encode(array("list" => $list, "total" => $total['c']));
        exit;
    }

    public function status($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (\Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    public function changeStatus($ids = '')
    {
        $ids = $this->request->post('ids');
        if (empty($ids)) {
            $this->error('没有选中!');
        }
        try {
            $result=$this->model->where("id","=",$ids)->field("status")->find();
            $v=$result->status==1?0:1;
            $this->model->where("id","=",$ids)->update(["status"=>$v]);
            $this->success('切换成功!');
        } catch (\Exception $e) {
            $this->error('切换失败!'.$e->getMessage());
        }
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if ($ids) {
            $count = Db::name('eb_apply_form_item_user')->where('form_id', 'in', $ids)->count();
            if ($count > 0) {
                $this->error('id号'.$ids.'的报名项目已有学生报名，不能删除');
            }

            $pk = $this->model->getPk();
            $adminIds = $this->getDataLimitAdminIds();
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $list = $this->model->where($pk, 'in', $ids)->select();

            $count = 0;
            Db::startTrans();
            try {
                foreach ($list as $k => $v) {
                    $count += $v->delete();
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            }
            if ($count) {
                $this->success();
            } else {
                $this->error('删除失败');
            }
        }
        $this->error(__('Parameter %s can not be empty', ''));
    }

    /**
     * 处理分阶段报名字段
     * @param array $params 请求参数
     */
    private function processStagedFields(&$params)
    {
        // 处理是否分阶段报名
        if (isset($params['is_staged'])) {
            $params['is_staged'] = intval($params['is_staged']);
        } else {
            $params['is_staged'] = 0;
        }
        
        // 处理阶段名称
        if (isset($params['staged_name'])) {
            $params['staged_name'] = trim($params['staged_name']);
        }
        
        // 处理stage数组格式的数据
        if (isset($params['stage']) && is_array($params['stage'])) {
            // 处理第一阶段
            if (isset($params['stage'][1])) {
                $stage1 = $params['stage'][1];
                if (isset($stage1['start_time'])) {
                    $params['stage1_start_time'] = $this->formatDateTime($stage1['start_time']);
                }
                if (isset($stage1['end_time'])) {
                    $params['stage1_end_time'] = $this->formatDateTime($stage1['end_time']);
                }
                if (isset($stage1['target'])) {
                    $params['stage1_target'] = intval($stage1['target']);
                }
            }
            
            // 处理第二阶段
            if (isset($params['stage'][2])) {
                $stage2 = $params['stage'][2];
                if (isset($stage2['start_time'])) {
                    $params['stage2_start_time'] = $this->formatDateTime($stage2['start_time']);
                }
                if (isset($stage2['end_time'])) {
                    $params['stage2_end_time'] = $this->formatDateTime($stage2['end_time']);
                }
                if (isset($stage2['target'])) {
                    $params['stage2_target'] = intval($stage2['target']);
                }
            }
            
            // 移除stage数组，避免保存到数据库
            unset($params['stage']);
        }
        
        // 处理扁平化格式的数据（兼容旧格式）
        if (isset($params['stage1_start_time'])) {
            $params['stage1_start_time'] = !empty($params['stage1_start_time']) ? $this->formatDateTime($params['stage1_start_time']) : null;
        }
        
        if (isset($params['stage1_end_time'])) {
            $params['stage1_end_time'] = !empty($params['stage1_end_time']) ? $this->formatDateTime($params['stage1_end_time']) : null;
        }
        
        if (isset($params['stage2_start_time'])) {
            $params['stage2_start_time'] = !empty($params['stage2_start_time']) ? $this->formatDateTime($params['stage2_start_time']) : null;
        }
        
        if (isset($params['stage2_end_time'])) {
            $params['stage2_end_time'] = !empty($params['stage2_end_time']) ? $this->formatDateTime($params['stage2_end_time']) : null;
        }
        
        // 处理报名对象字段
        if (isset($params['stage1_target'])) {
            $params['stage1_target'] = intval($params['stage1_target']);
        }
        
        if (isset($params['stage2_target'])) {
            $params['stage2_target'] = intval($params['stage2_target']);
        }
        
        // 验证分阶段报名的时间逻辑
        if ($params['is_staged'] == 1) {
            $this->validateStagedTimeLogic($params);
        }
        
        // 处理新增的五个设置项
        $this->processNewSettings($params);
    }
    
    /**
     * 格式化日期时间
     * @param string $datetime 日期时间字符串
     * @return string 格式化后的日期时间
     */
    private function formatDateTime($datetime)
    {
        if (empty($datetime) || $datetime === '') {
            return null;  // 返回 null 而不是空字符串
        }
        
        // 如果是时间戳，转换为日期时间格式
        if (is_numeric($datetime)) {
            return date('Y-m-d H:i:s', $datetime);
        }
        
        // 如果是日期时间字符串，直接返回
        return $datetime;
    }
    
    /**
     * 验证分阶段报名的时间逻辑
     * @param array $params 请求参数
     * @throws \think\Exception
     */
    private function validateStagedTimeLogic($params)
    {
        // 验证第一阶段时间
        if (!empty($params['stage1_start_time']) && !empty($params['stage1_end_time'])) {
            if (strtotime($params['stage1_start_time']) >= strtotime($params['stage1_end_time'])) {
                throw new \think\Exception('第一阶段开始时间不能晚于或等于结束时间');
            }
        }
        
        // 验证第二阶段时间
        if (!empty($params['stage2_start_time']) && !empty($params['stage2_end_time'])) {
            if (strtotime($params['stage2_start_time']) >= strtotime($params['stage2_end_time'])) {
                throw new \think\Exception('第二阶段开始时间不能晚于或等于结束时间');
            }
        }
        
        // 验证两个阶段的时间顺序
        if (!empty($params['stage1_end_time']) && !empty($params['stage2_start_time'])) {
            if (strtotime($params['stage1_end_time']) >= strtotime($params['stage2_start_time'])) {
                throw new \think\Exception('第一阶段结束时间必须早于第二阶段开始时间');
            }
        }
    }
    
    /**
     * 处理新增的五个设置项
     * @param array $params 请求参数
     */
    private function processNewSettings(&$params)
    {
        // 处理课程类型
        if (isset($params['course_type'])) {
            $params['course_type'] = intval($params['course_type']);
        }
        
        // 处理报名条件
        if (isset($params['enable_registration_conditions'])) {
            $params['enable_registration_conditions'] = intval($params['enable_registration_conditions']);
        } else {
            $params['enable_registration_conditions'] = 0;
        }
        
        if (isset($params['male_age_min'])) {
            $params['male_age_min'] = intval($params['male_age_min']);
        }
        
        if (isset($params['male_age_max'])) {
            $params['male_age_max'] = intval($params['male_age_max']);
        }
        
        if (isset($params['female_age_min'])) {
            $params['female_age_min'] = intval($params['female_age_min']);
        }
        
        if (isset($params['female_age_max'])) {
            $params['female_age_max'] = intval($params['female_age_max']);
        }
        
        if (isset($params['other_conditions'])) {
            $params['other_conditions'] = trim($params['other_conditions']);
        }
        
        // 处理报名须知
        if (isset($params['enable_terms_agreement'])) {
            $params['enable_terms_agreement'] = intval($params['enable_terms_agreement']);
        } else {
            $params['enable_terms_agreement'] = 0;
        }
        
        if (isset($params['terms_title'])) {
            $params['terms_title'] = trim($params['terms_title']);
        }
        
        if (isset($params['terms_content'])) {
            $params['terms_content'] = trim($params['terms_content']);
        }
        
        // 处理报名数量限制
        if (isset($params['enable_quantity_limit'])) {
            $params['enable_quantity_limit'] = intval($params['enable_quantity_limit']);
        } else {
            $params['enable_quantity_limit'] = 0;
        }
        
        // 处理每人最多可报课程数
        if (isset($params['max_courses_per_person'])) {
            $params['max_courses_per_person'] = $params['max_courses_per_person'] === '' ? null : intval($params['max_courses_per_person']);
        }
        
        // 处理报名表开启
        if (isset($params['enable_registration_form'])) {
            $params['enable_registration_form'] = intval($params['enable_registration_form']);
        } else {
            $params['enable_registration_form'] = 0;
        }
        
        if (isset($params['form_title'])) {
            $params['form_title'] = trim($params['form_title']);
        }
        
        if (isset($params['form_description'])) {
            $params['form_description'] = trim($params['form_description']);
        }
        
        // 处理必填字段（数组转JSON）
        if (isset($params['required_fields']) && is_array($params['required_fields'])) {
            $params['required_fields'] = json_encode($params['required_fields']);
        }
        
        // 处理手签板
        if (isset($params['enable_signature_pad'])) {
            $params['enable_signature_pad'] = intval($params['enable_signature_pad']);
        } else {
            $params['enable_signature_pad'] = 0;
        }
        
        if (isset($params['signature_position'])) {
            $params['signature_position'] = intval($params['signature_position']);
        }
        
        if (isset($params['signature_hint'])) {
            $params['signature_hint'] = trim($params['signature_hint']);
        }
        
        if (isset($params['signature_required'])) {
            $params['signature_required'] = intval($params['signature_required']);
        }
        
        // 处理事项设置
        if (isset($params['enable_matters_setting'])) {
            $params['enable_matters_setting'] = intval($params['enable_matters_setting']);
        } else {
            $params['enable_matters_setting'] = 0;
        }
        
        if (isset($params['matters_title'])) {
            $params['matters_title'] = trim($params['matters_title']);
        }
        
        if (isset($params['matters_content'])) {
            $params['matters_content'] = trim($params['matters_content']);
        }
        
        if (isset($params['matters_position'])) {
            $params['matters_position'] = intval($params['matters_position']);
        }
        
        // 处理线下报名
        if (isset($params['enable_offline_registration'])) {
            $params['enable_offline_registration'] = intval($params['enable_offline_registration']);
        } else {
            $params['enable_offline_registration'] = 0;
        }
        
        if (isset($params['offline_location'])) {
            $params['offline_location'] = trim($params['offline_location']);
        }
        
        if (isset($params['offline_contact'])) {
            $params['offline_contact'] = trim($params['offline_contact']);
        }
        
        if (isset($params['offline_phone'])) {
            $params['offline_phone'] = trim($params['offline_phone']);
        }
        
        if (isset($params['offline_hours'])) {
            $params['offline_hours'] = trim($params['offline_hours']);
        }
        
        // 处理其他开关字段
        if (isset($params['is_use_integral'])) {
            $params['is_use_integral'] = intval($params['is_use_integral']);
        } else {
            $params['is_use_integral'] = 0;
        }
        
        if (isset($params['is_real'])) {
            $params['is_real'] = intval($params['is_real']);
        } else {
            $params['is_real'] = 0;
        }
        
        if (isset($params['is_close'])) {
            $params['is_close'] = intval($params['is_close']);
        } else {
            $params['is_close'] = 0;
        }
        
        if (isset($params['is_opened'])) {
            $params['is_opened'] = intval($params['is_opened']);
        } else {
            $params['is_opened'] = 0;
        }
        
        if (isset($params['is_finished'])) {
            $params['is_finished'] = intval($params['is_finished']);
        } else {
            $params['is_finished'] = 0;
        }
        
        if (isset($params['is_user_end'])) {
            $params['is_user_end'] = intval($params['is_user_end']);
        } else {
            $params['is_user_end'] = 0;
        }
        
        if (isset($params['is_end'])) {
            $params['is_end'] = intval($params['is_end']);
        } else {
            $params['is_end'] = 0;
        }
        
        // 处理其他文本字段
        if (isset($params['intro'])) {
            $params['intro'] = trim($params['intro']);
        }
        
        if (isset($params['cover'])) {
            $params['cover'] = trim($params['cover']);
        }
        
        if (isset($params['table_id'])) {
            $params['table_id'] = intval($params['table_id']);
        }
        
        // 处理时间字段
        if (isset($params['dead_time'])) {
            $params['dead_time'] = !empty($params['dead_time']) ? $this->formatDateTime($params['dead_time']) : null;
        }
    }
    
    /**
     * 处理主要的时间字段
     * @param array $params 请求参数
     */
    private function processTimeFields(&$params)
    {
        $timeFields = ['start_time', 'end_time', 'dead_time'];
        
        foreach ($timeFields as $field) {
            if (isset($params[$field])) {
                if (empty($params[$field]) || $params[$field] === '') {
                    $params[$field] = null;
                } else {
                    $params[$field] = $this->formatDateTime($params[$field]);
                }
            }
        }
    }

}

